package cn.edu.seig.himusic.minio;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

public class MinioUtil {

  public static MinioClient getClient() {
    MinioClient minioClient =
        MinioClient.builder()
            .endpoint("http://localhost:9000")
            .credentials("admin", "admin")
            .build();
    return minioClient;
  }

  private String generateObjectPath(String endPoint, String bucket, String objectName) {
    return String.format("%s/%s/%s", endPoint, bucket, objectName);
  }

  public String uploadImageOneByMinio(File file) {
    String endPoint = "http://localhost:9000";
    String bucket = "bucket";
    String objName = file.getName();
    MinioClient minioClient = getClient();
    MultipartFile multipartFile = getMultipartFile(file, "file");
    try {
      minioClient.putObject(
          PutObjectArgs.builder().bucket(bucket).object(objName).stream(
                  multipartFile.getInputStream(), multipartFile.getSize(), -1)
              .contentType(multipartFile.getContentType())
              .build());

      String uploadUri = generateObjectPath(endPoint, bucket, objName);

      System.out.println(uploadUri);
      return uploadUri;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * 将File转化为MultipartFile
   *
   * @param file 示例，比如为："file"
   * @return
   */
  public static MultipartFile getMultipartFile(File file, String field) {
    try (InputStream input = Files.newInputStream(file.toPath())) {
      return new MockMultipartFile(field, input);
    } catch (Exception e) {
      throw new IllegalArgumentException("Invalid file: " + e, e);
    }
  }
}
